package org.red_cross_service.common.upload;

import lombok.extern.slf4j.Slf4j;
import org.red_cross_service.utils.QiniuKodoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.red_cross_service.common.anno.NoNeedToken;
import org.red_cross_service.common.response.Response;
import org.red_cross_service.utils.uuid.UUID;

import java.io.*;
import java.nio.file.Paths;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/api/file")
public class uploadController {

    @Value("${files.upload.path}")
    private String fileUploadDir;

    @Autowired
    QiniuKodoUtil qiniuKodoUtil;

    @RequestMapping("/upload")
    @NoNeedToken
    public Response fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) return Response.error("文件为空");

        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String[] strings = originalFilename.split("\\.");

        // 创建文件夹
        String uuid = UUID.randomUUID().toString();
        String dirPre =uuid + File.separator;
        File uploadDir = new File(fileUploadDir + dirPre);
        if (!uploadDir.exists()) uploadDir.mkdirs();

        // 保存上传文件
        String inputFilePath = Paths.get(uploadDir.getAbsolutePath(), uuid+"."+strings[strings.length-1]).toString();
        File oriFile = new File(inputFilePath);
        file.transferTo(oriFile);

        qiniuKodoUtil.upload(inputFilePath);

        if (strings[strings.length-1].equals("mp4")) {
//            String outputFilePath = Paths.get(uploadDir.getAbsolutePath(), uuid + ".m3u8").toString();
//            AsyncService bean = SpringUtils.getBean(AsyncService.class);
//            bean.asyncMethod(inputFilePath, outputFilePath, fileUploadDir);
            return Response.success("上传成功",  uuid+".mp4-M3U8.m3u8");
        }
        return Response.success("上传成功", dirPre + uuid +"."+strings[strings.length-1]);
    }
}
